public class MyBlockingQueue {
    private String[] items = new String[1000];
    //head 指向队列的头部
    private int head = 0;
    //tail 指向队列尾部的下一个元素 队列中有效元素范围为[head,tail)
    //当head和tail相等时,队列为空
    private int tail = 0;
    private volatile int size = 0;

    //入队列
    public synchronized void put(String elem) throws InterruptedException {
        while (size >= items.length) {
            //队列满
            //return;

                this.wait();

        }
        items[tail] = elem;
        tail++;
        //当tail到达末尾,就回到开头
        if (tail >= items.length) {
            tail = 0;
        }
        size++;
        this.notify();
        // 此时的wait用来唤醒入队列的wait
    }

    //出队列
    public synchronized String take() {
        while (items.length == 0) {
            //return null;
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        String elem = items[head];
        head++;
        if (head >= items.length) {
            head = 0;
        }
        size--;
        this.notify();
        //此处的notify用来唤醒入队列的wait
        return elem;
    }
}

class test {
    public static void main(String[] args){
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    queue.put(count + "");
                    System.out.println("生产元素: " + count);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String count = queue.take();
                    System.out.println("消费元素: " + count);

                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}